package gong.gm.filter.authFilter;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import gong.gm.mapper.SysUserMapper;
import gong.gm.pojo.dto.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @author voloiono
 * @date 2024/7/3 10:14
 */
@Component
public class JwtAuthFilter extends OncePerRequestFilter {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");

        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        JWT jwt = JWTUtil.parseToken(token);
        String key = (String) jwt.getPayload("key");
        System.out.println(key);

        SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .select(SysUser::getKey)
                .select(SysUser::getExpireTime)
                .eq(SysUser::getToken, token));

        boolean verified = JWTUtil.verify(token, sysUser.getKey().getBytes());
        if (verified) {
            sysUserMapper.update(new SysUser(), new LambdaUpdateWrapper<SysUser>()
                    .set(SysUser::getStatus, 1)
                    .set(SysUser::getLoginTime, new Date())
                    .set(SysUser::getLastLogin, new Date()));
            System.out.println("yes");
        } else {
            throw new RuntimeException("not login");
        }

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
